<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>员工列表</title>
    <%
        pageContext.setAttribute("APP_PATH",request.getContextPath());
    %>
    <%--引入jquery--%>
<%--
    $没有效果
    <script  src="${APP_PATH}/static/js/jquery-3.2.1.min.js"></script>
--%>
    <script src="${APP_PATH}/static/js/jquery-3.4.1.js"></script>
    <%--引入样式--%>
    <link href="${APP_PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="${APP_PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
</head>
<body>
<!-- 员工修改的模态框 -->
<div class="modal fade" id="empUpdateModal" tabindex="-1"
     role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">员工修改</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <%--员工名--%>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <p class="form-control-static" id="empName_update_static"></p>
                        </div>
                    </div>
                    <%--邮箱--%>
                    <div class="form-group">
                        <label for="email_update_input" class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="email" id="email_update_input" placeholder="email">
                            <span  class="help-block"></span>
                        </div>
                    </div>
                    <%--gender--%>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender1_update_input" value="M" checked>男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender2_update_input" value="F">女
                            </label>
                        </div>
                    </div>
                    <%--员工部门--%>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">deptName</label>
                        <div class="col-sm-4">
                            <%--部门提交部门id即可--%>
                            <select class="form-control" name="dId" id="dept_update_select">
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_update_btn">更新</button>
            </div>
        </div>
    </div>
</div>

<!-- 员工添加的模态框 -->
<div class="modal fade" id="empAddModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">员工添加</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <%--员工名--%>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="empName" id="empName_add_input" placeholder="empName">
                            <span  class="help-block"></span>
                        </div>
                    </div>
                    <%--邮箱--%>
                    <div class="form-group">
                        <label for="email_add_input" class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="email" id="email_add_input" placeholder="email">
                            <span  class="help-block"></span>
                        </div>
                    </div>
                    <%--gender--%>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender1_add_input" value="M" checked>男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender2_add_input" value="F">女
                            </label>
                        </div>
                    </div>
                    <%--员工部门--%>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">deptName</label>
                        <div class="col-sm-4">
                            <%--部门提交部门id即可--%>
                            <select class="form-control" name="dId" id="dept_add_select">

                            </select>
                        </div>
                        </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
            </div>
        </div>
    </div>
</div>
<%--搭建显示页面--%>
<div class="container">
    <%--标题--%>
    <div class="row">
        <div class="col-md-12">
            <h1>SSM-CRUD</h1>
        </div>
    </div>
    <%--按钮--%>
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <button class="btn-primary" id="emp_add_modal_btn">新增</button>
            <button class="btn-danger" id="emp_delete_all_btn">删除</button>
        </div>
    </div>
    <%--显示数据--%>
    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover" id="emps_table">
                <thead>
                <tr>
                    <th><input type="checkbox" id="check_all"/> </th>
                    <th>#</th>
                    <th>empName</th>
                    <th>gender</th>
                    <th>email</th>
                    <th>deptName</th>
                    <th>操作</th>
                </tr>
                </thead>
               <tbody>

               </tbody>

            </table>
        </div>
    </div>
    <%--显示分页信息--%>
    <div class="row">
        <%--分页文字信息--%>
        <div class="col-md-6" id="page_info_area">
        </div>
        <%--分页条--%>
        <div class="col-md-6" id="page_nav_area">

        </div>
    </div>
</div>
<script type="text/javascript">
<%--    定义总记录数--%>
    let totalRecord,currentpage ;
<%--    当页面加载完以后发送ajax请求，请求到分页数据--%>
    $(function () {
        to_page(1);
    });
//    跳转到某一页
    function to_page(pn) {
        $.ajax({
            url:"${APP_PATH}/emps",
            data:"pn="+pn,
            type:"GET",
            success:function (result) {
                console.log(result);
                //    解析并显示员工信息
                build_emps_table(result);
                //    解析并显示分页信息
                build_page_nav(result);
                //    解析并显示分页导航条信息
                build_page_info(result)
            }
        });
    }
//    解析并显示员工信息
    function build_emps_table(result) {
        $("#emps_table tbody").empty();
        $("#check_all").prop("checked",false);
        let emps = result.extend.pageInfo.list;
        $.each(emps,function (index,item) {
            let checkBoxTd = $("<td><input type='checkbox' class='check_item'></td>");
            let empIdTd = $("<td></td>").append(item.empId);
            let empNameTd = $("<td></td>").append(item.empName);
            let genderTd = $("<td></td>").append(item.gender=="M"?"男":"女");
            let emailTd = $("<td></td>").append(item.email);
            let departmentTd = $("<td></td>").append(item.department.deptName);
            let editBtn = $("<button></button>")
                .addClass("btn-primary btn-sm edit_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-pencil"))
                .append("编辑");
            editBtn.attr("edit-id",item.empId);
            let delBtn = $("<button></button>")
                .addClass("btn-danger btn-sm delete_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-trash"))
                .append("删除");
            delBtn.attr("del-id",item.empId);
            let btnTd = $("<td></td>").append(editBtn).append(" ").append(delBtn);
            $("<tr></tr>")
                .append(checkBoxTd)
                .append(empIdTd)
                .append(empNameTd)
                .append(genderTd)
                .append(emailTd)
                .append(departmentTd)
                .append(btnTd)
                .appendTo("#emps_table tbody");
        });
    }
//    解析并显示分页信息
    function build_page_info(result) {
        $("#page_info_area").empty();
    $("#page_info_area").append("当前"+result.extend.pageInfo.pageNum+"页，" +
        "总共" +result.extend.pageInfo.pages+"页，" +
        "共" +result.extend.pageInfo.total+"记录。");
    totalRecord = result.extend.pageInfo.total;
    currentpage = result.extend.pageInfo.pageNum;

}
//    解析并显示分页导航条信息
    function build_page_nav(result) {
        $("#page_nav_area").empty();
        let navEle = $("<nav></nav>");
        let ul = $("<ul></ul>").addClass("pagination");
        let firstPageLi=$("<li></li>").append($("<a></a>").attr("href","#").append("首页"));
        let prePageLi=$("<li></li>").append($("<a></a>").attr("href","#").append("&laquo;"));
        if (!result.extend.pageInfo.hasPreviousPage){
            firstPageLi.addClass("disabled");
            prePageLi.addClass("disabled");
        }else {
            firstPageLi.click(function () {
                to_page(1);
            });
            prePageLi.click(function () {
                to_page(result.extend.pageInfo.pageNum-1);
            });
        }

        ul.append(firstPageLi)
            .append(prePageLi);
        $.each(result.extend.pageInfo.navigatepageNums,function (index,item) {
            let numLi = $("<li></li>").append($("<a></a>").attr("href","#").append(item));
            if (result.extend.pageInfo.pageNum==item){
                numLi.addClass("active");
            }
            numLi.click(function () {
                to_page(item);
            });
            ul.append(numLi);
        });
        let nextPageLi=$("<li></li>").append($("<a></a>").attr("href","#").append("&raquo;"));
        let lastPageLi=$("<li></li>").append($("<a></a>").attr("href","#").append("末页"));
        if (!result.extend.pageInfo.hasNextPage){
            nextPageLi.addClass("disabled");
            lastPageLi.addClass("disabled");
        }else{
            nextPageLi.click(function () {
                to_page(result.extend.pageInfo.pageNum+1);
            });
            lastPageLi.click(function () {
                to_page(result.extend.pageInfo.pages);
            });
        }

        ul.append(nextPageLi)
            .append(lastPageLi);
        navEle.append(ul).appendTo("#page_nav_area");
    }
//    添加员工的模态框
    $("#emp_add_modal_btn").click(function () {
        // $("#empAddModal form")[0].reset();
        reset_form("#empAddModal form");
        //发送ajax请求，拿到部门信息，显示在下拉列表中
        getDepts("#empAddModal select");

        //弹出模态框
        $('#empAddModal').modal({
            backdrop:"static"
        });
    });
    //查询部门信息
    function getDepts(ele) {
        $(ele).empty();
        $.ajax({
            url: "${APP_PATH}/depts",
            type: "GET",
            success:function (result) {
                // console.log(result);
                // $("#dept_add_select")
                $.each(result.extend.depts,function () {
                    let optionEle = $("<option></option>").append(this.deptName).attr("value",this.deptId);
                    optionEle.appendTo(ele);

                });
            }
        });
    }
    //表单重置方法
    function reset_form(ele){
        $(ele)[0].reset();
        //清空表单样式及内容
        $(ele).find("*").removeClass("has-error has-success");
        $(ele).find(".help-block").text("");
    }
    //校验用户名是否可用
    $("#empName_add_input").change(function () {
        let empName = this.value;
        $.ajax({
            url:"${APP_PATH}/checkUser",
            type:"POST",
            data:"empName="+empName,
            success:function (result) {
                if (result.code==100){
                    show_validate_msg("#empName_add_input","success","用户名可用");
                    $("#emp_save_btn").attr("ajax_va","success");
                }else{
                    show_validate_msg("#empName_add_input","error",result.extend.va_msg);
                    $("#emp_save_btn").attr("ajax_va","error");
                }
            }
        });
    });
    //数据校验抽取方法
    function show_validate_msg(ele,status,msg) {
        $(ele).parent().removeClass("has-success has-error");
        $(ele).next("span").text("");
        if (status=="success"){
            $(ele).next("span").text(msg);
            $(ele).parent().addClass("has-success");
        }else if (status=="error"){
            $(ele).parent().addClass("has-error");
            // alert(msg);
            $(ele).next("span").text(msg);
        }

    }
    //表单校验方法
    function validate_add_from(){
        //校验用户名
        let empName = $("#empName_add_input").val();
        let regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
        if(!regName.test(empName)){
            show_validate_msg("#empName_add_input","error","用户名可以是2-5位中文或者6-16位英文和数字的组合");
            return false;
        }else {
            show_validate_msg("#empName_add_input","success","");
        }
    //    校验邮箱
        let email = $("#email_add_input").val();
        let regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        if(!regEmail.test(email)){
            show_validate_msg("#email_add_input","error","邮箱格式不正确");
            // $("#email_add_input").parent().addClass("has-error");
            // alert("邮箱格式不正确");
            return false;
        }else {
            show_validate_msg("#email_add_input","success","");
            // $("#email_add_input").next("span").text("");
            // $("#email_add_input").parent().addClass("has-success");
        }
        return true;
    }
    //保存员工信息
    $("#emp_save_btn").click(function () {
        //表单数据校验
        if (!validate_add_from()){
            return false;
        }
        //判断之前的ajax用户名校验请求是否成功
        if ($().attr("ajax-va")=="error"){
            return false;
        }
        //获取模态框的表单数据
        $.ajax({
            url:"${APP_PATH}/emp",
            type:"POST",
            data: $("#empAddModal form").serialize(),
            success:function (result) {
                // alert(result.msg);
                if (result.code==100){
                    // 关闭模态框
                    $("#empAddModal").modal("hide");
                    //        显示最后一页数据
                    to_page(totalRecord);
                }else {
                    if (undefined != result.extend.errorFields.empName){
                        show_validate_msg("#emp_add_input","error",result.extend.errorFields.empName)

                    }
                    if (undefined != result.extend.errorFields.email){
                        show_validate_msg("#email_add_input","error",result.extend.errorFields.email);

                    }
                }


            }

        });

    });
//    给按钮绑定单击事件
    $(document).on("click",".edit_btn",function () {
        // alert("edit");
        //   1.查出员工部门信息，并显示部门列表
        getDepts("#empUpdateModal select");
        //    2.查出员工信息
        getEmp($(this).attr("edit-id"));
    //    把员工的id传给更新按钮
        $("#emp_update_btn").attr("edit-id",$(this).attr("edit-id"));
    //    3.弹出模态框
        $("#empUpdateModal").modal({
            backdrop: "static"
        });
    })
    function getEmp(id) {
        $.ajax({
            url:"${APP_PATH}/emp/"+id,
            type:"GET",
            success:function (result) {
                let empData = result.extend.emp;
                $("#empName_update_static").text(empData.empName);
                $("#email_update_input").val(empData.email);
                $("#empUpdateModal input[name=gender]").val([empData.gender]);
                $("#empUpdateModal select").val([empData.dId]);

            }
        });
    }
//    点击更新，更新员工信息
    $("#emp_update_btn").click(function () {
    //判断邮箱是否合法
        //    校验邮箱
        let email = $("#email_update_input").val();
        let regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        if(!regEmail.test(email)){
            show_validate_msg("#email_update_input","error","邮箱格式不正确");
            return false;
        }else {
            show_validate_msg("#email_update_input","success","");
        }
        $.ajax({
            url:"${APP_PATH}/emp/"+$(this).attr("edit-id"),
            type:"PUT",
            data:$("#empUpdateModal form").serialize()+"&_method=put",
            success:function (result) {
                // alert(result.msg);
            //    关闭模态框
                $("#empUpdateModal").modal("hide");
            //    回到本页面
                to_page(currentpage);
            }
        });
    });
//    跟删除按钮绑定单击事件
$(document).on("click",".delete_btn",function () {
    let empName = $(this).parents("tr").find("td:eq(2)").text();
    let empId = $(this).attr("del-id");
    if (confirm("确认删除【"+empName+"】吗？")){
        $.ajax({
            url:"${APP_PATH}/emp/"+empId,
            type:"DELETE",
            success:function (result) {
                alert(result.msg);
                to_page(currentpage);
            }
        });
    }
});
//单击完成全选全不选
    $("#check_all").click(function () {
        $(".check_item").prop("checked",$("#check_all").prop("checked"));
    });
//    check_item
    $(document).on("click",".check_item",function () {
        //判断当前选中元素是否为5个
        let flag = $(".check_item:checked").length==$(".check_item").length;
        $("#check_all").prop("checked",flag);
    });
//点击全部删除，就批量删除
    $("#emp_delete_all_btn").click(function () {
        var empNames = "";
        var del_idstr = "";
        $.each($(".check_item:checked"),function () {
            empNames += $(this).parents("tr").find("td:eq(2)").text()+",";
            del_idstr += $(this).parents("tr").find("td:eq(1)").text()+"-";
        })
        //去除emps多余的,
        empNames = empNames.substring(0,empNames.length-1);
        del_idstr = del_idstr.substring(0,del_idstr.length-1);
        if(confirm("确认删除"+empNames+"吗?")){
            $.ajax({
                url:"${APP_PATH}/emp/"+del_idstr,
                type:"DELETE",
                success:function (result) {
                    alert(result.msg);
                    //回到本页
                    to_page(currentPage);
                }
            });
        }
    });
</script>
</body>
</html>
